package com.example.im.controller;

import com.example.im.model.User;
import com.example.im.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户注册接口
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> registerUser(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = userService.registerUser(user);
            if (success) {
                response.put("code", 200);
                response.put("message", "注册成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("code", 400);
                response.put("message", "用户名已存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "服务器错误");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    // 用户登录接口
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> loginUser(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();

        // 使用封装的 User 对象，调用登录验证服务
        User loginUser = userService.loginUser(user);

        if (loginUser != null) {
            response.put("code", 200);
            response.put("message", "登录成功");
            // 返回脱敏后的用户信息（仅用户名）
            Map<String, String> safeUser = new HashMap<>();
            safeUser.put("username", loginUser.getUsername());
            response.put("data", safeUser);
            return ResponseEntity.ok(response);
        } else {
            response.put("code", 401);
            response.put("message", "用户名或密码错误");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }


    // 获取用户信息（不返回密码）
    @GetMapping("/{username}")
    public ResponseEntity<Map<String, Object>> getUser(@PathVariable String username) {
        Map<String, Object> response = new HashMap<>();
        User user = userService.getUserByUsername(username);
        if (user != null) {
            Map<String, String> safeUser = new HashMap<>();
            safeUser.put("username", user.getUsername());
            response.put("code", 200);
            response.put("data", safeUser);
            return ResponseEntity.ok(response);
        } else {
            response.put("code", 404);
            response.put("message", "用户不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }
}